package com.innerchic.mapper.app;

import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.snackbar.SnackbarContentLayout;
import com.innerchic.annotations.base.ActivitySetting;
import com.innerchic.mapper.R;
import com.innerchic.mapper.app.base.Action;
import com.innerchic.mapper.app.base.DefaultSuperHolder;
import com.innerchic.mapper.app.base.Lifecycle;
import com.innerchic.mapper.log.Logger;
import com.innerchic.mapper.resfind.ResFind;
import com.innerchic.mapper.tool.SystemTool;
import com.innerchic.mapper.view.SwipeBackLayout;
import com.innerchic.sponsor.Sponsor;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Timer;
import java.util.TimerTask;

/**
 * ================================================
 * 作    者：贾恒飞 >>> 17515250730@163.com
 * 项    目：young
 * 日    期：2021/11/1 16:04
 * 包    名：com.innerchic.mapper.app
 * 描    述：超级Activity
 * Create by zFox from AndroidStudio4.2
 * ================================================
 */
public abstract class SuperActivity extends AppCompatActivity implements Lifecycle {

    /**
     * 当前页面设置
     */
    private final ActivitySetting activitySetting = this.getClass().getAnnotation(ActivitySetting.class);

    //------------------------------------当前子类所需帮助对象------------------------------------

    /**
     * UI线程handler对象
     */
    private Handler mainHandler;

    public synchronized Handler getMainHandler() {
        if (mainHandler == null) {
            mainHandler = new Handler(Looper.getMainLooper());
        }
        return mainHandler;
    }

    /**
     * 当前视图绑定器
     */
    private SuperHolder activityHolder = new DefaultSuperHolder();

    public void setActivityHolder(SuperHolder activityHolder) {
        this.activityHolder = activityHolder;
    }

    //------------------------------------Supper------------------------------------


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (activitySetting != null) {
            beforeInit();
            String layout = activitySetting.layout();
            setContentView(ResFind.getInstance().findLayout(layout));
            activityHolder.attachActivity(this);
            init();
            create();
        } else {
            loadError();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        resume();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //判断是否需要解绑定监听器
        if (activitySetting.observer()) {
            Sponsor.getDefault().unregister(this);
        }
        destroy();
        activityHolder.close();
        activityHolder = null;
        mainHandler = null;
    }

    //------------------------------------Lifecycle------------------------------------

    @Override
    public void beforeInit() {
        //是否使用SwipeBack
        if (activitySetting.swipe()) {
            try {
                @SuppressLint("InflateParams")
                SwipeBackLayout layout = (SwipeBackLayout) LayoutInflater.from(this).inflate(R.layout.layout_swipe_back, null);
                layout.attachToActivity(this);
            } catch (Exception e) {
                showToast("布局配置器异常,SwipeBackLayout暂时停用.");
            }
        }
        //绑定Holder
        if (activitySetting.bind().equals(ActivitySetting.ResHolder)) {
            createViewBindActivityHolder();
        }
    }

    /**
     * 尝试创建视图Holder
     */
    protected void createViewBindActivityHolder() {
        try {
            Field[] declaredFields = this.getClass().getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if (SuperHolder.class.isAssignableFrom(declaredField.getType())) {
                    declaredField.setAccessible(true);
                    declaredField.set(this, declaredField.getType().newInstance());
                    activityHolder = (SuperHolder) declaredField.get(this);
                    return;
                }
            }
            Logger.d("当前类不存在相关的视图Holder.");
        } catch (Exception e) {
            e.printStackTrace();
            Logger.d("创建视图Holder失败异常.");
        }
    }

    @Override
    public void init() {
        //是否使用沉浸式状态栏
        if (activitySetting.fullScreen()) {
            SystemTool.fullScreen(this);
        } else {
            if (activitySetting.modificationActionBar()) {
                SystemTool.setStatusBarColor(topBarColor(), this);
            }
        }
        //设置页面顶部字颜色
        SystemTool.setTopFontColor(this, activitySetting.textTheme());
        //初始化页面参数
        if (activitySetting.bind().equals(ActivitySetting.ResBind)) {
            ResFind.getInstance().bind(this);
        } else if (activitySetting.bind().equals(ActivitySetting.ResFind)) {
            ResFind.getInstance().find(this);
        }
        //判断是否需要绑定监听器
        if (activitySetting.observer()) {
            Sponsor.getDefault().register(this);
        }
    }

    @Override
    public void start() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void stop() {

    }

    @Override
    public void loadError() {
        showToast("布局加载失败,找不到入口配置");
    }

    //------------------------------------Tool------------------------------------

    /**
     * 检查是否有对应权限
     *
     * @param permission 要检查的权限
     */
    public boolean verifyPermissions(java.lang.String permission) {
        int Permission = ActivityCompat.checkSelfPermission(this, permission);
        return Permission == PackageManager.PERMISSION_GRANTED;
    }

    /**
     * 获取旋转动画
     */
    protected Animation rotate() {
        return AnimationUtils.loadAnimation(this, R.anim.image_loading_anim);
    }

    /**
     * 设置文本下划线
     *
     * @param textView 文本
     */
    protected void textUnderline(TextView textView) {
        if (textView == null) return;
        textView.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        textView.getPaint().setAntiAlias(true);
    }

    /**
     * 获取列表默认提供的样式
     */
    protected LayoutAnimationController getRecyclerAnim() {
        LayoutAnimationController controller = new LayoutAnimationController(AnimationUtils.loadAnimation(this, R.anim.item_animation));
        controller.setOrder(LayoutAnimationController.ORDER_NORMAL);
        controller.setDelay(0.2f);//前面还没结束，后面已经开始，实现连续
        return controller;
    }

    /**
     * 显示Toast
     *
     * @param msg    消息
     * @param values 值
     */
    protected void showToast(String msg, Object... values) {
        Toast toast = Toast.makeText(SuperApplication.getApplication(), getMsg(msg, values), Toast.LENGTH_SHORT);
        toast.show();
    }

    /**
     * 获取消息
     *
     * @param msg    消息
     * @param values 值
     * @return String
     */
    protected String getMsg(String msg, Object... values) {
        if (msg == null) return "";
        if (values != null) {
            for (Object o : values) {
                msg = msg.replaceFirst("@-", String.valueOf(o));
            }
        }
        return msg;
    }

    /**
     * 显示SnackBar
     *
     * @param view    view
     * @param actions 动作
     */
    protected void showSnack(View view, String msg, Action... actions) {
        Snackbar snackbar = Snackbar.make(view, msg, Snackbar.LENGTH_LONG);
        //使用反射获取TextView并赋值
        if (actions != null && actions.length > 0) {
            Action action = actions[0];
            snackbar.setAction(action.getName(), action.getListener());
            try {
                Class<?> superclass = snackbar.getClass().getSuperclass();
                if (superclass != null) {
                    Field view1 = superclass.getDeclaredField("view");
                    view1.setAccessible(true);
                    Object o = view1.get(snackbar);
                    if (o == null) return;
                    Method childAt = o.getClass().getMethod("getChildAt", int.class);
                    childAt.setAccessible(true);
                    Object invoke = childAt.invoke(o, 0);
                    SnackbarContentLayout contentLayout = (SnackbarContentLayout) invoke;
                    if (contentLayout == null) return;
                    @SuppressLint("RestrictedApi")
                    TextView tv = contentLayout.getActionView();
                    tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
                    tv.getPaint().setAntiAlias(true);
                }
            } catch (NoSuchFieldException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }
        snackbar.show();
    }

    //------------------------------------双击退出------------------------------------

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (backAfter()) {
                if (activitySetting != null && activitySetting.backTows()) {
                    backForTows();
                } else {
                    back(null);
                }
            }
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    /**
     * 标记是否启动了一次
     */
    private boolean isOut = false;

    //返回提示
    protected String backStr = "再按一次返回键退出";

    /**
     * 点击两次返回键退出当前页模式
     */
    private void backForTows() {
        if (isOut) {
            back(null);
        } else {
            isOut = true;
            showToast(backStr);
            //开始计时
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new TimerTask() {
                        @Override
                        public void run() {
                            isOut = false;
                            this.cancel();
                        }
                    });
                }
            }, 2000);
        }
    }

    /**
     * 是否由注解控制返回操作
     *
     * @return 默认true是
     */
    protected boolean backAfter() {
        return true;
    }

    /**
     * 回退
     */
    public void back(View view) {
        finish();
    }

    //------------------------------------是否全屏显示------------------------------------

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (activitySetting != null && activitySetting.fill()) {
            if (hasFocus) {
                View decorView = getWindow().getDecorView();
                decorView.setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
            }
        }
    }

    //------------------------------------Abstract------------------------------------

    protected int topBarColor() {
        return R.color.colorAccent;
    }

}
